package com.akk.module.authentication;

import com.akk.exception.RestBusinessException;
import com.akk.module.authentication.model.request.AuthRequest;
import com.akk.module.authentication.model.request.CompanyAuthRequest;
import com.akk.module.authentication.model.response.AuthResponse;
import com.akk.module.authentication.model.response.CompanyAuthResponse;
import com.akk.utils.Constants;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class CompanyAuthService extends AuthService {

    private static CompanyAuthService companyAuthService;

    private Logger logger = LoggerFactory.getLogger(CompanyAuthService.class);


    public static CompanyAuthService getInstance() {
        if(companyAuthService == null)
            companyAuthService = new CompanyAuthService();
        return companyAuthService;
    }

    @Override
    public AuthResponse auth(AuthRequest request) {
        JSONObject content = new JSONObject();
        CompanyAuthRequest companyAuthRequest = (CompanyAuthRequest)request;
        content.put("busiName", companyAuthRequest.getBusName());//营业执照全称
        content.put("busiNo", companyAuthRequest.getBusNumber());//营业执照注册号
        content.put("acctName", companyAuthRequest.getAcctName());//对公账户名
        content.put("acctNo", companyAuthRequest.getAcctNumber());//对公账号
        content.put("bankNo", companyAuthRequest.getBankNumber());//清算联行号
        JSONObject json = getAuthMessage(Constants.AUTH_USER_CODE,
                Constants.AUTH_APP_CODE,companyAuthRequest.getCompanyReason(),content);
        JSONObject result = sendEncMessage(json.toString(),
                Constants.AUTH_COMPANY_URL,
                Constants.AUTH_COMPANY_APP_KEY,
                Constants.AUTH_VECTOR,
                Constants.AUTH_USER_CODE,
                Constants.AUTH_COMPANY_PRIVATE_KEY);
        if(result.has("data")){
            //正确报文
            JSONArray dataArray = result.getJSONArray("data");
            JSONObject dataObject = (JSONObject) dataArray.get(0);

            return (AuthResponse) JSONObject.toBean(dataObject, CompanyAuthResponse.class);
        }
        //错误报文
        JSONObject msgObject = result.getJSONObject("msg");
        logger.error("企业实名认证出错.-->状态码:"+msgObject.get("code")+"/详情:"+msgObject.get("codeDesc"));
        throw new RestBusinessException("实名认证失败.");
    }
}
